package cn.haut.online_read.controller.crawler.zhuishushenqi;

import cn.haut.online_read.crawler.BookBySearchCrawler;
import cn.haut.online_read.crawler.BookNameBySearchCrawler;
import cn.haut.online_read.utils.CrawlerUtils;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.pipeline.ConsolePipeline;
import us.codecraft.webmagic.pipeline.ResultItemsCollectorPipeline;

/**
 * @author xing
 * @date 2021-04-25 14:21
 */
@Controller(value = "searchController")
@RequestMapping
@Slf4j
public class SearchController {

    public static final String BASE_SEARCH_URL = "https://www.zhuishushenqi.com/search?val=";

    @GetMapping(value = {"/search"})
    @ResponseBody
    public String search(
            @RequestParam("val") String val,
            @RequestParam(value = "page", required = false) Integer page
    ) {
        String result = "";
        // 为空 直接返回空 TODO 返回 code: 0
        if(val == null || val.isBlank()){
            return result;
        }
        String url = "";
        if( page == null) {
            url = BASE_SEARCH_URL + val;
        } else {
            url = BASE_SEARCH_URL + val + "&page=" + page;
        }
        // TODO 添加返回代码，表示结果为空或错误，失败，例如 code:0
        return CrawlerUtils.getJsonResult(new BookBySearchCrawler(), url);
    }

    /**
     * 与上边不同，这个只获取书名，并且 json 里 对应属性为 value
     *
     * @param val
     * @return
     */
    @GetMapping(value = {"/getNames"})
    @ResponseBody
    public String getNames(
            @RequestParam("val") String val
    ){
        String result = "";
        String url = BASE_SEARCH_URL + val;
        ResultItemsCollectorPipeline resultItemsCollectorPipeline = new ResultItemsCollectorPipeline();

        Spider.create(new BookNameBySearchCrawler())
                .addUrl(url)
                .addPipeline(new ConsolePipeline())
                .addPipeline(resultItemsCollectorPipeline)
                .run();

        if(!resultItemsCollectorPipeline.getCollected().isEmpty()){
            result = JSON.toJSONString(resultItemsCollectorPipeline.getCollected().get(0).getAll());
        }
        return result;
    }
}
